package com.sky.service.impl;

import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.BusinessDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 导出运营数据
     *
     * @param response HttpServletResponse
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 查询近30天运营数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.MAX);
        // 查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

        // ApachePOI读取excel模版，并写入数据
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        if(is == null) {
            throw new RuntimeException("文件不存在");
        }
        try {
            // 创建工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            // 根据表名称索引获取表
            XSSFSheet sheet = workbook.getSheetAt(0);
            // 根据行号获取行（行号从0开始）
            XSSFRow row = sheet.getRow(1);
            // 根据列号获取当前行单元格（列号从0开始）
            XSSFCell cell = row.getCell(1);
            /* 设置时间范围 */
            // 设置单元格值 - 日期范围
            cell.setCellValue("时间：" + beginDate + " 至 " + endDate);

            /* 设置概览数据 */
            // 获取第4行数据
            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover()); // 获取并设置第3列数据 - 营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); // 获取并设置第5列数据 - 订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers()); // 获取并设置第7列数据 - 新增用户数
            // 获取第5行数据
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount()); // 获取并设置第3列数据 - 有效订单
            row.getCell(4).setCellValue(businessData.getUnitPrice()); // 获取并设置第5列数据 - 平均客单价

            /* 设置明细数据 */
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                beginTime = LocalDateTime.of(date, LocalTime.MIN);
                endTime = LocalDateTime.of(date, LocalTime.MAX);
                // 查询每天数据
                businessData = workspaceService.getBusinessData(beginTime, endTime);
                // 从第8行开始获取数据
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(beginTime.toLocalDate().toString()); // 日期
                row.getCell(2).setCellValue(businessData.getTurnover()); // 营业额
                row.getCell(3).setCellValue(businessData.getValidOrderCount()); // 有效订单
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); // 订单完成率
                row.getCell(5).setCellValue(businessData.getUnitPrice()); // 平均客单价
                row.getCell(6).setCellValue(businessData.getNewUsers()); // 新增用户数
            }

            /* 响应文件写出，并关流（先开后关） */
            workbook.write(response.getOutputStream());
            workbook.close();
            is.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
